package com.littlebee.storysuper.activity;

import android.Manifest;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.littlebee.storysuper.R;
import com.littlebee.storysuper.common.sharePrefUtils.SharePrefUtil;
import com.littlebee.storysuper.entry.LastTwothanksAudio;
import com.littlebee.storysuper.entry.User;
import com.littlebee.storysuper.utils.Constant;
import com.littlebee.storysuper.utils.DeviceUtil;
import com.littlebee.storysuper.utils.GsonUtils;
import com.littlebee.storysuper.utils.LogUtil;
import com.littlebee.storysuper.utils.NetWorkUtils;
import com.littlebee.storysuper.utils.ToastUtil;
import com.littlebee.storysuper.utils.Utils;
import com.littlebee.storysuper.widget.AlwaysMarqueeTextView;
import com.littlebee.storysuper.widget.RoundAngleImageView;
import com.tuliu.appupdate.updatelib.UpdateManager;
import com.zss.library.PermissionCallBack;
import com.zss.library.activity.BaseActivity;
import com.zss.library.adapter.CommonAdapter;
import com.zss.library.adapter.ViewHolder;
import com.zss.library.toolbar.CommonToolbar;
import com.zss.library.utils.LogUtils;
import com.zss.library.utils.SharedPrefUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.im.android.api.JMessageClient;
import cn.jpush.im.android.api.model.UserInfo;
import cn.jpush.im.api.BasicCallback;


/**
 * 主页
 * <p>
 * 13916014463
 */
public class MainActivity extends BaseActivity implements View.OnClickListener, SwipeRefreshLayout.OnRefreshListener {
    /**
     * 主页的四个大控件啊
     */
    RoundAngleImageView iv1, iv2, iv3, iv4;
    /**
     * 主页有可能用到下拉刷新
     */
    private SwipeRefreshLayout mSwipeLayout;
    private static final int REFRESH_COMPLETE = 0X110;
    List<UserInfo> mList;
    JSONObject object;
    AlwaysMarqueeTextView message_tv_pop;
    SharedPreferences sharedPreferences;
    public static final String HASBINDDEVICEID = "hasbinddeviceid";
    boolean isNewPhoto;
    ImageView isNew;
    private ListView lv;
    LastTwothanksAudio lastTwothanksAudio;
    List<Info> infos;
    CommonAdapter<Info> mAdapter;
    private UpdateManager updateMan;
    private ProgressDialog updateProgressDialog;
    public static boolean isForeground = false;
    public static final String MESSAGE_RECEIVED_ACTION = "com.example.jpushdemo.MESSAGE_RECEIVED_ACTION";
    public static final String KEY_TITLE = "title";
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";
    private MessageReceiver mMessageReceiver;

    @Override
    public int getLayoutResId() {
        return R.layout.activity_main;
    }

    @Override
    public void initView() {
        super.initView();
        sharedPreferences = getSharedPreferences(Constant.appName, Context.MODE_PRIVATE); //私有数据
        isNewPhoto = getIntent().getBooleanExtra("isNewPhoto", false);
        iv1 = (RoundAngleImageView) findViewById(R.id.photo1);
        iv2 = (RoundAngleImageView) findViewById(R.id.photo2);
        iv3 = (RoundAngleImageView) findViewById(R.id.photo3);
        iv4 = (RoundAngleImageView) findViewById(R.id.photo4);
        isNew = (ImageView) findViewById(R.id.show_is_new);

        lv = (ListView) findViewById(R.id.lv);
        if (isNewPhoto == true) {
            isNew.setVisibility(View.VISIBLE);
        } else {
            isNew.setVisibility(View.GONE);
        }
        message_tv_pop = (AlwaysMarqueeTextView) findViewById(R.id.message_tv_pop);
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.id_swipe_ly);

        mSwipeLayout.setOnRefreshListener(this);

        initUpdate();

        String rid = JPushInterface.getRegistrationID(getApplicationContext());
        if (!rid.isEmpty()) {
            LogUtil.d("liaoyong:regid:" + rid);
            SharedPrefUtils prefUtils = Utils.getSharedPrefCommonFile();
            prefUtils.put("pushId", rid);
        } else {
            Toast.makeText(this, "Get registration fail, JPush init failed!", Toast.LENGTH_SHORT).show();
        }

        registerMessageReceiver();  // used for receive msg
    }
    /**
     * 检测更新
     */
    private void initUpdate() {
        String checkUrl = String.format("%s?phoneId=%s&version_code=%d",
                Constant.VerionUrl, DeviceUtil.getDevicePhone(this), getAppVersion(this));
        LogUtils.d("dd", "checkurl:" + checkUrl);
        UpdateManager.checkUpdate(this, false, true, checkUrl, new UpdateManager.CheckUpdateListener() {
            @Override
            public void onResult(final boolean result, Bundle bundle, int ext) {
            }
        });
    }
    /**
     * 获取当前应用版本code
     * @return
     */
    public static int getAppVersion(Context context) {
        int versionCode = 0;
        PackageManager manager = context.getPackageManager();
        try {
            PackageInfo info = manager.getPackageInfo(context.getPackageName(), 0);
            versionCode = info.versionCode; //版本名
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }
    @Override
    public void initData(Bundle savedInstanceState) {
        super.initData(savedInstanceState);
        iv1.setOnClickListener(this);
        iv2.setOnClickListener(this);
        iv3.setOnClickListener(this);
        iv4.setOnClickListener(this);
        verifyPermissions(MainActivity.this, Manifest.permission.RECORD_AUDIO,
                new String[]{Manifest.permission.RECORD_AUDIO, Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE}
                , 0x01, new PermissionCallBack() {

                    @Override
                    public void onGranted() {
                        ToastUtil.displayShortToast("grant permission");
                    }

                    @Override
                    public void onDenied() {
                    }
                });
        getInfo();
        getVoice();
        getInfoBind();
        bingMessage();
    }

    @Override
    public void setTopBar() {
        super.setTopBar();
        setStatusBarColor(R.color.module_video_bg);
        CommonToolbar toolbar = getToolbar();
        toolbar.setBgRes(R.color.module_video_bg);
        toolbar.setTitle(getString(R.string.app_name));
        TextView textView = new TextView(this);
        textView.setTextColor(Color.WHITE);
        textView.setTextSize(16);
        textView.setText("    绑定");
        toolbar.setLeftView(textView);
        textView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017/8/14
                if (Utils.isLogin()) {
                    Intent intent = new Intent(MainActivity.this, BindActivity.class);
                    startActivityForResult(intent, 0x01);
                } else {
                    Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                    startActivity(intent);
                }
            }


        });
        toolbar.setRightText("我的");
        toolbar.setOnRightListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // TODO: 2017/8/14
                if (Utils.isLogin()) {
                    Intent intent = new Intent(MainActivity.this, SettingBabyInfoActivity.class);
                    intent.putExtra("isFirst", false);
                    startActivity(intent);
                } else {
                    Intent intent = new Intent(MainActivity.this, RegisterActivity.class);
                    startActivityForResult(intent, 100);
                }
            }
        });

    }

    @Override
    protected void onResume() {
        isForeground = true;
        super.onResume();
    }


    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {
            case R.id.photo1:
                if (Utils.isLogin()) {
                    intent = new Intent(MainActivity.this, TodayStoryActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(MainActivity.this, RegisterActivity.class);
                    startActivityForResult(intent, 100);

                }
                break;
            case R.id.photo2:

                if (Utils.isLogin()) {
                    intent = new Intent(MainActivity.this, EnglishActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(MainActivity.this, RegisterActivity.class);
                    startActivityForResult(intent, 100);

                }
                break;
            case R.id.photo3:

                if (Utils.isLogin()) {
                    intent = new Intent(MainActivity.this, ChatActivity.class);

                    startActivity(intent);
                } else {
                    intent = new Intent(MainActivity.this, RegisterActivity.class);
                    startActivityForResult(intent, 100);

                }
                break;
            case R.id.photo4:
                if (Utils.isLogin()) {
                    isNewPhoto = false;
                    isNew.setVisibility(View.GONE);
                    intent = new Intent(MainActivity.this, PhotoActivity.class);
                    startActivity(intent);
                } else {
                    intent = new Intent(MainActivity.this, RegisterActivity.class);
                    startActivityForResult(intent, 100);

                }


                break;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == 0x01) {

            } else if (requestCode == 100) {
                com.zss.library.utils.LogUtils.i("XHX", "XHX:执行了回调");
                getInfo();
                getInfoBind();
                bingMessage();
            }

        }

    }

    @Override
    public void onRefresh() {
        getInfo();
        getInfoBind();
        bingMessage();
    }

    /**
     * 刷新首页数据啦
     */
    public void getInfo() {
        User user = Utils.getUserEntry();
        if (user != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("phoneId", user.getMobile());
            // TODO: 2017/8/15
            NetWorkUtils.post(MainActivity.this, "getoperatinginfo", map, false, new NetWorkUtils.IListener() {

                @Override
                public void onSuccess(String result, JSONObject resObj) {
                    LogUtils.i("XHX", "XHXSUCC:" + result);
                    object = resObj;
                    mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 0);

                }

                @Override
                public void onError(String result, String code, String msg) {
                    LogUtils.i("XHX", "XHXERROR:" + result);
                    mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 0);


                }
            });
        }
    }

    /**
     * 获取绑定信息
     */
    public void getInfoBind() {
        User user = Utils.getUserEntry();
        if (user != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("phoneId", user.getMobile());
            // TODO: 2017/8/15
            NetWorkUtils.post(MainActivity.this, "gethasbinddevice", map, false, new NetWorkUtils.IListener() {

                @Override
                public void onSuccess(String result, JSONObject resObj) {
                    LogUtils.i("XHX", "XHXSUCCBind:" + result);
                    try {
                        SharePrefUtil.getInstance(MainActivity.this).setObject(SharePrefUtil.HASBINDDEVICEID, resObj.getJSONObject("response").getString("hasbinddeviceid"));
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void onError(String result, String code, String msg) {
                    LogUtils.i("XHX", "XHXERRORBind:" + result);
                }
            });
        }
    }

    private Handler mHandler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            switch (msg.what) {
                case REFRESH_COMPLETE:
                    // TODO: 2017/8/15
                    mSwipeLayout.setRefreshing(false);
                    if (object != null) {
                        try {
                            message_tv_pop.setText(object.getJSONObject("response").getString("todayusers")
                                    + "        " + object.getJSONObject("response").getString("mystorys")
                                    + "        " + object.getJSONObject("response").getString("productdescribe"));
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                    break;

            }
        }

    };

    /**
     * 获取最近留言
     */
    public void getVoice() {
        User user = Utils.getUserEntry();
        if (user != null) {
            HashMap<String, String> map = new HashMap<>();
            map.put("phoneId", user.getMobile());
            // TODO: 2017/8/15
            NetWorkUtils.post(MainActivity.this, "getlasttwothanksaudio", map, false, new NetWorkUtils.IListener() {

                @Override
                public void onSuccess(String result, JSONObject resObj) {
                    LogUtils.i("XHX", "XHXSUCC:" + result);
                    String res = resObj.optString("response");
                    lastTwothanksAudio = GsonUtils.getObjFromJSON(res, LastTwothanksAudio.class);
                    Info info = new Info(lastTwothanksAudio.getAudio1time(), lastTwothanksAudio.getAudio1url());
                    Info info1 = new Info(lastTwothanksAudio.getAudio2time(), lastTwothanksAudio.getAudio2url());
                    infos = new ArrayList<Info>();
                    infos.add(info);
                    infos.add(info1);
                    mAdapter = new CommonAdapter<Info>(getActivity(), R.layout.layout_item_main_voice) {
                        @Override
                        protected void convert(ViewHolder viewHolder, final Info workerListEntry, final int i) {
                            final ImageView name = viewHolder.findViewById(R.id.number_tv);
                            if (workerListEntry == null || TextUtils.isEmpty(workerListEntry.time))
                                return;
                            TextView name1 = viewHolder.findViewById(R.id.tv);
                            name1.setText(workerListEntry.time.substring(0, workerListEntry.time.length() - 2));
                            name.setImageResource(R.mipmap.player_big);
                            if (mPlayer != null) {
                                if (mPlayer.isPlaying()) {
                                    if (infos.get(i).url.equals(playerPath)) {
                                        name.setImageResource(R.mipmap.pause_big);
                                    }
                                }
                            }
                            name.setOnClickListener(new View.OnClickListener() {
                                @Override
                                public void onClick(View v) {
                                    if (mPlayer == null) {
                                        name.setImageResource(R.mipmap.pause_big);
                                        startPlayer(infos.get(i).url);
                                    } else {
                                        if (infos.get(i).url.equals(playerPath)) {
                                            if (mPlayer.isPlaying()) {
                                                name.setImageResource(R.mipmap.player_big);

                                                mPlayer.pause();

                                            } else {
                                                name.setImageResource(R.mipmap.pause_big);

                                                mPlayer.start();

                                            }
                                        } else {
                                            name.setImageResource(R.mipmap.pause_big);
                                            mediaRelease();
                                            startPlayer(infos.get(i).url);
                                            notifyDataSetChanged();

                                        }
                                    }
                                }
                            });
                        }
                    };
                    lv.setAdapter(mAdapter);
                    mAdapter.addAll(infos);

                }

                @Override
                public void onError(String result, String code, String msg) {


                }
            });
        }
    }

    /**
     * 登录极光IM
     */
    private void bingMessage() {
        User user = Utils.getUserEntry();
        if (user != null) {
            JMessageClient.login(user.getMobile(), user.getPassword(), new BasicCallback() {
                @Override
                public void gotResult(int responseCode, String LoginDesc) {
                    if (responseCode == 0) {
                        //getInfoIm();
                    } else {
                        Toast.makeText(getActivity(), "IM注册失败", Toast.LENGTH_SHORT).show();
                    }
                }
            });
        }


    }

    @Override
    protected void onPause() {
        mediaRelease();
        isForeground = false;
        super.onPause();
    }

    @Override
    protected void onDestroy() {
        LocalBroadcastManager.getInstance(this).unregisterReceiver(mMessageReceiver);
        super.onDestroy();
    }

    class Info {
        String time;
        String url;

        public Info() {
        }

        public Info(String time, String url) {
            this.time = time;
            this.url = url;
        }
    }

    private MediaPlayer mPlayer = null;
    private String playerPath = "";

    private void startPlayer(String item) {
        mPlayer = new MediaPlayer();
        mPlayer.setOnErrorListener(new MediaPlayer.OnErrorListener() {
            public boolean onError(MediaPlayer mp, int what, int extra) {
                mediaRelease();
                return true;
            }
        });
        mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
            @Override
            public void onCompletion(MediaPlayer mp) {
                mAdapter.notifyDataSetChanged();
                mediaRelease();

            }
        });
        try {
            mPlayer.setDataSource(item);
            final AudioManager audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            if (audioManager.getStreamVolume(AudioManager.STREAM_ALARM) != 0) {
                mPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mPlayer.setLooping(false);
                playerPath = item;
                mPlayer.prepare();
                mPlayer.start();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void mediaRelease() {
        if (mPlayer != null) {
            mPlayer.release();
            mPlayer = null;
        }
    }


    //push recieve
    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_RECEIVED_ACTION);
        LocalBroadcastManager.getInstance(this).registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            try {
                if (MESSAGE_RECEIVED_ACTION.equals(intent.getAction())) {
                    String messge = intent.getStringExtra(KEY_MESSAGE);
                    String extras = intent.getStringExtra(KEY_EXTRAS);
                    StringBuilder showMsg = new StringBuilder();
                    showMsg.append(KEY_MESSAGE + " : " + messge + "\n");
                    if (!TextUtils.isEmpty(extras)) {
                        showMsg.append(KEY_EXTRAS + " : " + extras + "\n");
                    }
                    setCostomMsg(showMsg.toString());
                }
            } catch (Exception e){
            }
        }
    }

    private void setCostomMsg(String msg){
        ToastUtil.displayLongToast("recv :" + msg);
    }

}
